﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Configuration;
namespace Common.Library.Db
{
    /// <summary>
    /// 数据库工厂   用来创建数据库对象
    /// </summary>
    public class AppDBContextFactory
    {
        /// <summary>
        /// 数据库连接字符串
        /// </summary>
        static string connStr = ConfigurationManager.ConnectionStrings["Conn"].ToString();

        /// <summary>
        /// ThreadLocal  每个线程使用当前线程内的数据库对象
        /// ThreadLocal  会在进程中管理一个列表  key = 线程ID value = IAppDBContext 的实例
        /// 只要当前线程没有释放，能保证，当前线程中都使用同一个对象。
        /// </summary>
        private static ThreadLocal<IAppDBContext> appUnitOfWorkThreaLocal = new ThreadLocal<IAppDBContext>();


        /// <summary>
        /// 获取数据库对象
        /// </summary>
        /// <returns></returns>
        public static IAppDBContext GetAppDBContext()
        {
            if (appUnitOfWorkThreaLocal.Value == null ||
                appUnitOfWorkThreaLocal.Value.IsDisposed())
            {
                appUnitOfWorkThreaLocal.Value = CreateAppDBContext();
            }
            return appUnitOfWorkThreaLocal.Value;
        }


        /// <summary>
        /// 创建数据库对象
        /// </summary>
        /// <returns></returns>
        private static IAppDBContext CreateAppDBContext()
        {
            ///***** 这里要通过IoC来确定创建的实例
            IAppDBContext appDBContext = new AppDBContextDapper(connStr);
            return appDBContext;
        }


    }
}
